package com.xindong.paking.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindong.paking.dtos.CarouselChartDTO;
import com.xindong.paking.dtos.CarouselChartDTO01;
import com.xindong.paking.dtos.PageResult;
import com.xindong.paking.exception.CustomerException;
import com.xindong.paking.mapper.CarouselChartMapper;
import com.xindong.paking.entity.CarouselChart;
import com.xindong.paking.service.CarouselChartService;
import com.xindong.paking.utils.FileUtil;
import com.xindong.paking.utils.Result;
import com.xindong.paking.utils.StringUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

import static com.xindong.paking.entity.constant.Constants.*;

@Service
public class CarouselChartServiceImpl extends ServiceImpl<CarouselChartMapper, CarouselChart> implements CarouselChartService {

    @Autowired
    CarouselChartMapper carouselChartMapper;

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

    LinkedBlockingQueue<String> blockingDeque = new LinkedBlockingQueue<>();


    @Override
    public Result queryByConForPage(CarouselChartDTO dto) {

        LambdaQueryWrapper<CarouselChart> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(StringUtil.isNotEmpty(dto.getId()),CarouselChart::getId,dto.getId())
                .like(StringUtil.isNotEmpty(dto.getName()),CarouselChart::getName,dto.getName())
                .eq(StringUtil.isNotEmpty(dto.getStatus()),CarouselChart::getStatus,dto.getStatus());

        if (StringUtil.isEmpty(dto.getPageCount())){
            dto.setPageCount(DEFAULT_PAGE_COUNT);
        }
        if (StringUtil.isEmpty(dto.getPageCount())){
            dto.setPageCount(DEFAULT_PAGESIZE);
        }
        IPage<CarouselChart> page = new Page<>(getCurrentPage(dto.getPageCount(), dto.getPageSize()),dto.getPageSize());
        page = this.page(page, queryWrapper);
        //封装结果
        PageResult pageResult = new PageResult(page.getRecords(),page.getTotal(), (int) page.getCurrent(), (int) page.getSize());



        return Result.success(DEFAULT_QUERY_SUCCESS_MSG,pageResult);
    }

    @Override
    public Result queryByStatus(String status) {

        LambdaQueryWrapper<CarouselChart> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(CarouselChart::getStatus,status);

        List<CarouselChart> carouselCharts = carouselChartMapper.selectList(queryWrapper);


        return Result.success(DEFAULT_QUERY_SUCCESS_MSG,carouselCharts);


    }



    @Override
    @Transactional
    public Result deleteById(List<Integer> carouselChartIds) {

        if(StringUtil.isEmpty(carouselChartIds)){
            return Result.error(DEFAULT_DELETE_NULL);
        }
        ArrayList<String> ossKeys = new ArrayList<>();
        carouselChartIds.forEach(v->{
            LambdaQueryWrapper<CarouselChart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CarouselChart::getId,v)
                    .select(CarouselChart::getOssKey);
            CarouselChart carouselChart = carouselChartMapper.selectOne(queryWrapper);
            ossKeys.add(carouselChart.getOssKey());
            int i = carouselChartMapper.deleteById(v);
            if (i < 1){
                throw new CustomerException("删除图片失败");
            }
        });

        //异步删除服务器上的图片,放入阻塞队列
        ossKeys.forEach(v->{
            blockingDeque.offer(v);
        });

        fixedThreadPool.submit(new Runnable() {
            @Override
            public void run() {
                blockingDeque.forEach(v->{
                    FileUtil.deleteFile(v);
                });
            }
        });


        return Result.success(DEFAULT_DELETE_SUCCESS_MSG);
    }




    @Override
    public Result insertCarouselChart(CarouselChartDTO01 dto) {
//        String[] upload = FileUtil.upload(dto.getFile());
//        if (StringUtil.isEmpty(upload)){
//            return Result.error(DEFAULT_INSERT_FAIL_MSG);
//        }
        if (StringUtil.isEmpty(dto.getStatus())){
            dto.setStatus("Y");
        }
        CarouselChart carouselChart = new CarouselChart();
        if (StringUtil.isNotEmpty(dto.getName())){
            carouselChart.setName(dto.getName());
        }
        if (StringUtil.isNotEmpty(dto.getSort())){
            carouselChart.setSort(dto.getSort());
        }
        carouselChart.setStatus(dto.getStatus());
        carouselChart.setIcon(dto.getIcon());
//        carouselChart.setOssKey(upload[0]);
        carouselChart.setCreateTime(new Date());
        boolean save = save(carouselChart);
        if (save){
            return Result.success(DEFAULT_INSERT_SUCCESS_MSG);
        }

        return Result.error(DEFAULT_INSERT_FAIL_MSG);
    }

    @Override
    public Result updateCarouselChart(CarouselChartDTO01 dto) {
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(dto.getId());
//        deleteById(integers);

//        String[] upload = FileUtil.upload(dto.getFile());

        LambdaUpdateWrapper<CarouselChart> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CarouselChart::getName,dto.getName())
                .set(CarouselChart::getSort,dto.getSort())
                .set(CarouselChart::getStatus,dto.getStatus())
                .set(CarouselChart::getIcon,dto.getIcon())
//                .set(CarouselChart::getOssKey,upload[0])
                .eq(CarouselChart::getId,dto.getId());
        boolean update = update(updateWrapper);

        if (update){
            return Result.success(DEFAULT_UPDATE_SUCCESS_MSG);
        }

        return Result.error(DEFAULT_UPDATE_FAIL_MSG);
    }


    /**
     * 计算当前页是第几条数据
     * @param pageCount 当前页
     * @param pageSize 每页条数
     * @return
     */
    private Integer getCurrentPage(Integer pageCount, Integer pageSize) {
        return (pageCount - 1)*pageSize;
    }

}
